import { Box, Popover } from '@mui/material'
import React, { useEffect, useState } from 'react'
import { PhotoshopPicker } from 'react-color'
import reactCSS from 'reactcss'

interface Props {
  color: string
  onColorChange: (value: string) => void
}

export default function ColorPicker({
  color,
  onColorChange
}: Props) {
  const [anchorEl, setAnchorEl] = React.useState<HTMLDivElement | null>(null);
  const [c, setC] = useState<string>(color)

  const styles = reactCSS({
    'default': {
      color: {
        width: '100%',
        height: '14px',
        borderRadius: '2px',
        background: color
      } as React.CSSProperties,
      swatch: {
        width: '100%',
        padding: '5px',
        background: '#fff',
        borderRadius: '1px',
        boxShadow: '0 0 0 1px rgba(0,0,0,.1)',
        display: 'inline-block',
        cursor: 'pointer',
      } as React.CSSProperties,
      popover: {
        position: 'absolute',
        zIndex: 2,
      } as React.CSSProperties,
      cover: {
        position: 'fixed',
        top: '0px',
        right: '0px',
        bottom: '0px',
        left: '0px',
      } as React.CSSProperties,
    },
  });

  useEffect(() => {
    console.log('color', color)
    setC(color)
  }, [])

  const showPopover = (event: React.MouseEvent<HTMLDivElement>) => {
    setAnchorEl(event.currentTarget);
  }
  const hidePopover = () => {
    console.log('hidePopover')
    setAnchorEl(null);
  }
  const open = Boolean(anchorEl);
  const id = open ? 'simple-popover' : undefined;

  const handleChange = (c: any) => {
    setC(c.hex)
  }
  const handleAcceptChange = () => {
    console.log('handleAcceptChange', c)
    onColorChange(c)
    hidePopover()
  }

  return (
    <Box sx={{ width: '100%' }}>
      <div style={styles.swatch} onClick={e => showPopover(e)}>
        <div style={styles.color} />
      </div>
      <Popover
        id={id}
        open={open}
        anchorEl={anchorEl}
        anchorOrigin={{
          vertical: 'center',
          horizontal: 'right',
        }}
      >
        <PhotoshopPicker color={c} onChange={handleChange} onAccept={handleAcceptChange} onCancel={hidePopover} />
      </Popover>
    </Box >
  )
}
